import urllib.request
import urllib.parse
import os

# 从HTML文件中提取的PDF URL（原始URL）
original_url = "https://moor-smile.shec.edu.cn/rest/pdf/20250808/84519de1-8bb4-4bd1-b3fa-e610b20d4408/学生社交媒体与人际关系数据集.pdf"

# 正确编码URL，只编码路径部分
url_parts = list(urllib.parse.urlparse(original_url))
url_parts[2] = urllib.parse.quote(url_parts[2])  # 编码path部分
pdf_url = urllib.parse.urlunparse(url_parts)

# 定义保存的文件名和路径
save_dir = r'd:\D'
pdf_filename = '学生社交媒体与人际关系数据集.pdf'
pdf_save_path = os.path.join(save_dir, pdf_filename)

# 下载PDF文件
try:
    print(f"开始下载PDF文件...")
    print(f"原始URL: {original_url}")
    print(f"编码后URL: {pdf_url}")
    print(f"保存路径: {pdf_save_path}")
    
    # 创建请求对象，添加用户代理以模拟浏览器请求
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
    req = urllib.request.Request(pdf_url, headers=headers)
    
    # 下载文件
    with urllib.request.urlopen(req) as response, open(pdf_save_path, 'wb') as out_file:
        data = response.read()
        out_file.write(data)
    
    # 检查文件是否成功下载
    if os.path.exists(pdf_save_path):
        file_size = os.path.getsize(pdf_save_path) / 1024 / 1024  # 转换为MB
        print(f"PDF文件下载成功！")
        print(f"保存路径: {pdf_save_path}")
        print(f"文件大小: {file_size:.2f} MB")
    else:
        print("PDF文件下载失败，文件不存在。")
        exit(1)

except Exception as e:
    print(f"下载PDF文件时发生错误: {e}")
    exit(1)